package top.techqi.usbd.desc

import top.techqi.core.kext.WORD_T
import top.techqi.core.util.FmtUtil

class EdptDesc(
    val bEndpointAddress: Byte,
    val bmAttributes: Byte,
    val wMaxPacketSize: Short,
    val bInterval: Byte
) : AbstractDesc(LENGTH, TYPE) {
    constructor(bytes: ByteArray) : this(
        bytes[2],
        bytes[3],
        WORD_T(bytes[5], bytes[4]),
        bytes[6]
    ) {
        require(bytes[0] == LENGTH && bytes[1] == TYPE) {
            "Invalid length or type: ${bytes[0]}, ${bytes[1]}"
        }
    }

    override fun toString(): String {
        return """
        EdptDesc(
            bEndpointAddress = %1${'$'}s,
            bmAttributes     = %2${'$'}s,
            wMaxPacketSize   = %3${'$'}s,
            bInterval        = %4${'$'}s
        )
        """.trimIndent().format(
            "%1\$s(%2\$d.%3\$d.%4\$d)".format(
                FmtUtil.toBinString(bEndpointAddress),
                (bEndpointAddress.toInt() shr 7) and 0x01,
                (bEndpointAddress.toInt() shr 4) and 0x03,
                (bEndpointAddress.toInt() shr 0) and 0x0f,
            ),
            FmtUtil.toBinString(bmAttributes),
            wMaxPacketSize,
            bInterval
        )
    }

    companion object {
        const val TYPE: Byte = 0x05
        const val LENGTH: Byte = 7
    }
}
